<?
include("conf.inc.php");
include("functions.php");

session_start();

switch($_GET['action']) {
case "login":
	dbConnect();
	
	// Lösenordet ska ändå sha1-hashas så det kan inte användas för injections
	$sSql = "SELECT * FROM tblMedlemmar WHERE " .
			"email = '" . mysql_real_escape_string($_POST['email']) . "' AND " .
			"passHash = '" . sha1($_POST['password']) . "'";
	$result = mysql_query($sSql) or die(mysql_error());
	
	if($row = mysql_fetch_array($result)) {
		// TODO: Här ska sessionen admin också sparas om man är admin...
		$_SESSION['medlemId'] = $row['id'];
		
		$sSql = "UPDATE tblMembers SET 
				inloggningar = inloggningar + 1, 
				inloggad = NOW() 
				WHERE id = '" . $_SESSION['medlemId'] . "' ";
		mysql_query($sSql);
		
		if(isset($_POST['remember'])) {
			// id@hash, gäller i ett år
			setcookie("login", $row['id'] . "@" . sha1($_POST['password']), time() + 365 * 86400);
		}	
	}
	
	mysql_close();
	
	$returnTo = isset($_POST['returnTo']) ? $_POST['returnTo'] : "/";
		
	header("Location: " . $returnTo);
	
	break;
case "logout":
	session_destroy();
	
	setcookie("login", "", time() - 1);
	
	header("Location: /");
	
	break;
case "memberSearch":
	// Uppdaterar alla sök-sessioner om söktermerna verkar vettiga
	
	if(preg_match("/^[0-9]{1,2}$/", $_POST['regionsId'])) {
		$_SESSION['memberSearch']['regionsId'] = $_POST['regionsId'];
	}
	
	if(preg_match("/^[0-9]{1}$/", $_POST['orderBy'])) {
		$_SESSION['memberSearch']['orderBy'] = $_POST['orderBy'];
	}
	
	if($_POST['q'] != "Frisökning") {
		$_SESSION['memberSearch']['q'] = addslashes(strip_tags($_POST['q']));
	} else {
		$_SESSION['memberSearch']['q'] = "";
	}
	
	$_SESSION['memberSearch']['endastBild'] = isset($_POST['endastBild']) ? 1 : 0;
	
	header("Location: /medlemmar/sida1.php");
	
	break;
}
?>